/*
 *
 *  Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
 *  SPDX-License-Identifier: Apache-2.0
 *
 */
import { useCallback, useState } from 'react';
import {
  fetchCertList,
  fetchDeleteCert,
  fetchDeleteNode,
  fetchDeleteOrg,
  fetchDetailCert,
  fetchDownloadCert,
  fetchGenerateCert,
  fetchImportCert,
  fetchOneGenerateCert,
  fetchNodeSave, fetchUpgradeNode, fetchDowngradeNode,
} from '.';
import {
  ICertItem,
  IDetailCertParam,
  IDownloadCertParam,
  IFetchCertListParam,
  IGenerateCertParam,
  IImportCertParam,
  IDetailCertResponse,
  NodeDelParms,
  OrgDelParms,
  NodeSaveParam,
} from './interface';
import { useDispatchMessage } from 'src/utils/hooks';
import { saveBlobAs } from '../../../utils/common';
import { Error, ErrorCode } from 'src/common/interface';
import { Modal } from 'tea-component';

/**
 * 获取证书列表
 */
export function useFetchCertList() {
  const { errorNotification } = useDispatchMessage();
  const [list, setList] = useState<ICertItem[]>([]);
  const [totalCount, setTotalCount] = useState<number>(0);

  const fetch = useCallback(async (params: IFetchCertListParam) => {
    try {
      const result = await fetchCertList(params);
      setList(result.data.Response.GroupList);
      setTotalCount(result.data.Response.TotalCount);
    } catch (err) {
      errorNotification({
        title: '获取证书列表失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return { list, totalCount, fetch };
}
/**
 * 快速生成证书
 */
export function useFetchOneGenCert() {
  const { errorNotification } = useDispatchMessage();
  const fetchOneGenCert = useCallback(async () => {
    try {
      const data = await fetchOneGenerateCert();
      return data.data.Response.Data.Status;
    } catch (err) {
      errorNotification({
        title: '一键生成证书失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return { fetchOneGenCert };
}
/**
 * 查看证书
 */
export function useFetchCertDetail() {
  const { errorNotification } = useDispatchMessage();
  const [privateKey, setPrivateKey] = useState<string>('');
  const [publicKey, setPublicKey] = useState<string>('');
  const [certDetail, setCertDetail] = useState<{
    SignCertDetail?: string;
    SignKeyDetail?: string;
    TlsCertDetail?: string;
    TlsKeyDetail?: string;
  }>({});
  const fetch = useCallback(async (params: IDetailCertParam) => {
    try {
      const result = await fetchDetailCert(params);
      const data: IDetailCertResponse = result.data.Response.Data;
      setPublicKey(data.PublicKey);
      setPrivateKey(data.PrivateKey);
      setCertDetail(data);
      // data.CertDetail
    } catch (err) {
      errorNotification({
        title: '获取证书失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return {
    certDetail,
    privateKey,
    publicKey,
    fetch,
  };
}

/**
 * 删除证书
 */
export function useFetchRemoveCertDetail() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const fetchRemoveCert = useCallback(async (params: IDetailCertParam, isPublic?: boolean) => {
    const yes = await Modal.confirm({
      message: '删除确认',
      description: isPublic ? '请确定是否删除该账户？' : '请确定是否删除该证书？',
      okText: '删除',
      cancelText: '取消',
    });
    if (!yes) {
      return;
    }
    try {
      const result = await fetchDeleteCert(params);
      if (result.status === 200) {
        successNotification({
          description: '删除证书成功',
        });
      }
    } catch (err) {
      errorNotification({
        title: '删除证书失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return {
    fetchRemoveCert,
  };
}

/**
 * 删除节点
 */
export function useFetchRemoveNode() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const fetchRemoveNode = useCallback(async (params: NodeDelParms) => {
    const yes = await Modal.confirm({
      message: '移除确认',
      description: '请确定是否移除该节点？',
      okText: '移除',
      cancelText: '取消',
    });
    if (!yes) {
      return;
    }
    try {
      const result = await fetchDeleteNode(params);
      if (result.status === 200) {
        successNotification({
          description: '申请移除节点成功',
        });
      }
    } catch (err) {
      errorNotification({
        title: '申请移除节点失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return {
    fetchRemoveNode,
  };
}

/**
 * 删除组织
 */
export function useFetchRemoveOrg() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const fetchRemoveOrg = useCallback(async (params: OrgDelParms) => {
    const yes = await Modal.confirm({
      message: '移除确认',
      description: '请确定是否移除该组织？',
      okText: '移除',
      cancelText: '取消',
    });
    if (!yes) {
      return;
    }
    try {
      const result = await fetchDeleteOrg(params);
      if (result.status === 200) {
        successNotification({
          description: '申请移除组织成功',
        });
      }
    } catch (err) {
      errorNotification({
        title: '申请移除组织失败',
        description: (err as Error).Message,
      });
    }
  }, []);

  return {
    fetchRemoveOrg,
  };
}

/**
 * 下载证书
 */
export function useFetchDownloadCert() {
  const { errorNotification } = useDispatchMessage();
  const fetch = useCallback(async (params: IDownloadCertParam) => {
    try {
      const result = await fetchDownloadCert(params);
      const { data: blob, headers } = result;
      saveBlobAs(headers, blob);
    } catch (err) {
      errorNotification({
        title: '下载证书失败',
        description: (err as Error).Message,
      });
    }
  }, []);
  return {
    fetch,
  };
}

/**
 * 申请证书
 */
export function useFetchGenerateCert() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const [isSuccess, setIsSuccess] = useState<boolean>(false);
  const fetch = useCallback(async (params: IGenerateCertParam) => {
    try {
      await fetchGenerateCert(params);
      setIsSuccess(true);
      successNotification({
        description: '申请证书成功',
      });
    } catch (err) {
      errorNotification({
        title: '申请证书失败',
        description: (err as Error).Message,
      });
    }
  }, []);
  return {
    isSuccess,
    fetch,
  };
}

export function saveNode() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const [isSuccess, setIsSuccess] = useState<boolean>(false);
  const fetch = useCallback(async (params: NodeSaveParam) => {
    try {
      await fetchNodeSave(params);
      setIsSuccess(true);
      successNotification({
        description: '添加节点成功',
      });
    } catch (err) {
      errorNotification({
        title: '添加节点失败',
        description: (err as Error).Message,
      });
    }
  }, []);
  return {
    isSuccess,
    fetch,
  };
}


export function useUpgradeNode() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const [isSuccess, setIsSuccess] = useState<boolean>(false);
  const upgradeNode = useCallback(async (params: NodeDelParms) => {
    try {
      await fetchUpgradeNode(params);
      setIsSuccess(true);
      successNotification({
        description: '申请升级节点成功',
      });
    } catch (err) {
      errorNotification({
        title: '申请升级节点失败',
        description: (err as Error).Message,
      });
    }
  }, []);
  return {
    isSuccess,
    upgradeNode,
  };
}

export function useDowngradeNode() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const [isSuccess, setIsSuccess] = useState<boolean>(false);
  const downgradeNode = useCallback(async (params: NodeDelParms) => {
    try {
      await fetchDowngradeNode(params);
      setIsSuccess(true);
      successNotification({
        description: '申请降级节点成功',
      });
    } catch (err) {
      errorNotification({
        title: '申请降级节点失败',
        description: (err as Error).Message,
      });
    }
  }, []);
  return {
    isSuccess,
    downgradeNode,
  };
}


/**
 * 导入证书
 */
export function useFetchImportCert() {
  const { errorNotification, successNotification } = useDispatchMessage();
  const fetch = useCallback(async (params: IImportCertParam) => {
    try {
      await fetchImportCert(params);
      successNotification({
        description: '导入证书成功',
      });
    } catch (err) {
      let errMessage = '导入证书失败';
      switch ((err as Error)?.Code) {
        case ErrorCode.AccountExisted:
          errMessage = '该账户已存在，请检查后重新输入。';
          break;
        case ErrorCode.AccountKeyMatch:
          errMessage = '公私钥对不匹配，请检查后重新上传。';
          break;
        case ErrorCode.AlgorithmMatch:
          errMessage = '公私钥对与所选密码算法不符，请检查后重新上传。';
          break;
      }
      errorNotification({
        title: errMessage,
        description: (err as Error).Message,
      });
    }
  }, []);

  return {
    fetch,
  };
}
